package com.oliet.aspect;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import com.oliet.common.dto.log.ControllerLogDTO;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;


/**
 * @className: ControllerLogsAspect
 * @Description: 控制层日志切面类
 * @author: JiaZhenpeng
 * @data: 2022/12/28 14:38
 */
@Component
@Slf4j
@Aspect
public class ControllerLogsAspect {

    /**
     * 切入点
     */
    @Pointcut("execution(public * com.oliet.controller.*Controller.*(..))")
    public void controllerPath() {
    }


    @Around("controllerPath()")
    public Object aroundControllerLog(ProceedingJoinPoint pjp) throws Throwable {
        // 获取请求参数
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();

        // 记录执行时间
        long startTime = System.currentTimeMillis();
        //处理请求
        Object result = pjp.proceed();
        try {
            ControllerLogDTO logDto = ControllerLogDTO.builder()
                    .time(new Date())
                    .url(request.getRequestURL().toString())
                    .httpMethod(request.getMethod())
                    .classMethod(String.format("%s.%s"
                            , pjp.getSignature().getDeclaringTypeName()
                            , pjp.getSignature().getName()))
                    .requestParams(getRequestParam(pjp))
                    .result(result)
                    .costTimes(System.currentTimeMillis() - startTime).build();

            log.info("记录Controller接口日志:\n接口路径:{},\n执行耗时:{} 毫秒,\n请求类.方法:{},\n请求参数:{},\n执行返回数据:{}",
                    logDto.getUrl(),
                    logDto.getCostTimes(),
                    logDto.getClassMethod(),
                    JSONObject.toJSONString(logDto.getRequestParams()),
                    JSONObject.toJSONString(logDto.getResult()));
        } catch (Exception e) {
            log.warn("记录请求日志失败:{}", e);
        }
        return result;
    }


    /**
     * 获取请求参数
     */
    private Object[] getRequestParam(ProceedingJoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        Object[] arguments = new Object[args.length];
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[i] instanceof MultipartFile) {
                continue;
            }
            arguments[i] = args[i];
        }
        return arguments;
    }


}
